'use strict'

const originalMorgan = require('morgan');

exports = module.exports = morgan;

morgan.compile = originalMorgan.compile
morgan.format = originalMorgan.format
morgan.token = originalMorgan.token

function morgan(format, options) {
  const fn = originalMorgan(format, options)
  return (ctx, next) => {
    return new Promise((resolve, reject) => {
      let req = Object.assign({}, ctx.req);
      req._CUSTOM_ = { ip: ctx.request.ip };
      fn(req, ctx.res, (err) => {
        err ? reject(err) : resolve(ctx)
      })
    }).then(next);
  };
}